package com.kaifamiao.month03.day0331.bank.service;

import com.kaifamiao.month03.day0331.bank.dao.AccountDao;
import com.kaifamiao.month03.day0331.bank.dao.StatementDao;
import com.kaifamiao.month03.day0331.bank.model.Account;
import com.kaifamiao.month03.day0331.bank.model.Statement;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class BankService {

    Scanner in = new Scanner(System.in);
    AccountDao dao = new AccountDao();
    Account login = new Account();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    SimpleDateFormat cdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS"); // 生成流水号 格式
    StatementDao statementDao = new StatementDao();

    public void start() {
        initialize();
        menu();
    }

    private void menu() {
        print("欢迎来到开发喵银行！");
        print("请输入您要执行的操作：");
        print("1.开户");
        print("2.登录");
        print("3.查询所有用户");
        print("4.查询所有流水");
        print("0.退出");
        int type = in.nextInt();
        selectType(type, 0);
    }

    // 登录界面
    private void loginMenu() {
        Date date = new Date();
        print(login.getName() + " ，您好，欢迎光临开发喵银行" + "，" + sdf.format(date) + "!");
        print("请输入您要执行的操作：");
        print("1.查看账户信息");
        print("2.存款");
        print("3.查询余额");
        print("4.修改信息");
        print("5.取款");
        print("6.查询流水");
        print("9.注销账户");
        print("0.退出登录");
        int type = in.nextInt();
        selectType(type, 1);
    }

    private void selectType(int type, int i) {
        if (i == 0) {
            switch (type) {
                case 1 -> createAccount();
                case 2 -> login();
                case 3 -> findAll();
                case 4 -> showAllStatement();
                case 0 -> exit();
            }
        } else if (i == 1) {
            switch (type) {
                case 1 -> showAccount();
                case 2 -> deposit();
                case 3 -> findMoney();
                case 4 -> modify();
                case 5 -> withdrawal();
                case 6 -> showStatement();
                case 9 -> closeAccount();
                case 0 -> logout();
            }
        }
    }



    // 未登录用户功能
    // 开户
    private void createAccount() {
        print("请输入姓名：");
        String name = in.next();
        print("请输入密码：");
        String pass = in.next();
        print("请再次确认密码：");
        String passTwo = in.next();
        while (true) {
            if (pass.equals(passTwo))
                break;
            else
                print("两次密码不一致");
            print("请重新输入密码：");
            pass = in.next();
            print("请再次确认密码：");
            passTwo = in.next();
        }
        print("请输入手机号：");
        String phone = in.next();
        print("请输入年龄：");
        int age = in.nextInt();
        print("请输入性别");
        char gender = in.next().charAt(0);
        long card = System.currentTimeMillis();
        Account account = new Account(name, pass, phone, age, gender, card);
        dao.save(account);
        printErr("开户成功，是否登录？（输入y 登录）");
        String input = in.next();
        if ("y".equals(input)) {
            login = account;
            loginMenu();
        } else
            menu();
    }

    private void initialize() {
        for (int i = 0; i < 4; i++) {
            String name = "test" + i;
            String pass = "123456";
            String phone = "1234567890" + i;
            int age = 18 + i;
            char gender = '女';
            long card = System.currentTimeMillis() + i;
            Account account = new Account(name, pass, phone, age, gender, card);
            dao.save(account);
        }
    }

    // 登录
    private void login() {
        print("请输入手机号：");
        String phone = in.next();
        print("请输入密码：");
        String pass = in.next();
        Account account = dao.isRight(phone, pass);
        if (account != null) {
            login = account;
            loginMenu();
        } else {
            printErr("用户名或密码错误！！");
            login();
        }
    }

    // 查询所有用户信息
    private void findAll() {
        Account[] accounts = dao.findAll();
        for (Account ac : accounts) {
            print(ac.toString());
        }
        menu();
    }

    // 查询所有用户流水
    private void showAllStatement() {
        for (Statement statement : statementDao.findAll()) {
            printErr(statement.toString());
        }
        menu();
    }

    // 退出系统
    private void exit() {
        print("欢迎下次光临！");
        System.exit(0);
    }

    // 登录之后的用户功能
    // 查看用户信息
    private void showAccount() {
        Account account = dao.showAccount(login.getPhone());
        print(account.toString());
        loginMenu();
    }

    // 存款业务
    private void deposit() {
        print("请输入存款金额：（元）");
        double money = in.nextDouble();
        login.setMoney(money, 1);
        print("成功存款 " + money + " 元！");
        String number = cdf.format(new Date());
        addStatement(0, number, money);
        loginMenu();
    }

    // 添加流水记录
    private void addStatement(int n, String number, double money) {
        Statement statement = new Statement(login.getName(), n, number, login.getCard(), money);
        statementDao.save(statement);
    }

    // 查询余额
    private void findMoney() {
        print("账户余额： " + login.getMoney() + " 元！");
        loginMenu();
    }

    // 取款业务
    private void withdrawal() {
        print("请输入取款金额：");
        double money = in.nextDouble();
        while (!checkMoney(money)) {
            printErr("你有多少钱，自己心里没有数吗？");
            print("请输入取款金额：");
            money = in.nextDouble();
        }
        login.setMoney(money, 0);
        String number = cdf.format(new Date());
        addStatement(1, number, money);
        printErr("取款成功！");
        loginMenu();
    }

    // 检查取款是否合法
    private boolean checkMoney(double money) {
        return money <= login.getMoney();
    }

    // 修改用户信息
    private void modify() {
        print("选择你要修改的信息：");
        print("1.姓名 ");
        print("2.电话 ");
        print("3.性别 ");
        print("4.密码 ");
        print("5.年龄 ");
        print("0.退出修改 ");
        int type = in.nextInt();
        modifyAccount(type);
    }

    private void modifyAccount(int type) {
        print("请输入修改的信息：");
        switch (type) {
            case 1 -> {
                String name = in.next();
                login.setName(name);
            }
            case 2 -> {
                String phone = in.next();
                login.setPhone(phone);
            }
            case 3 -> {
                char gender = in.next().charAt(0);
                login.setGender(gender);
            }
            case 4 -> {
                String pass = in.next();
                print("请确认密码：");
                String rePass = in.next();
                while (!pass.equals(rePass)) {
                    print("两次密码不一致");
                    pass = in.next();
                    print("确认密码：");
                    rePass = in.next();
                }
                login.setPass(pass);
            }
            case 5 -> {
                int age = in.nextInt();
                login.setAge(age);
            }
            case 0 -> loginMenu();
        }
        print("修改完成！");
        modify();
    }

    // 查询用户流水
    private void showStatement() {
        Statement[] statements = statementDao.showStatement(login.getCard());
        for (Statement sta : statements) {
            print(sta.toString());
        }
        loginMenu();
    }

    // 注销账户
    private void closeAccount() {
        if (dao.remove(dao.getIndex(login)) != null) {
            printErr("注销成功！");
            login = null;
            menu();
        } else {
            printErr("注销失败！");
        }
    }

    // 退出登录
    private void logout() {
        login = null;
        menu();
    }

    private void print(String str) {
        System.out.println(str);
    }

    private void printErr(String str) {
        System.err.println(str);
    }
}
